import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author 龙小虬
 * @date 2021/4/23 13:32
 */
public class AtomicTryLock {


    //定义AtomicInteger
    //0表示该锁已经被使用
    //1表示未被使用
    private volatile AtomicInteger atomicInteger = new AtomicInteger(0);

    // 存放当前获取到锁的线程名
    private Thread lockCurrentThread;

    //尝试获取锁
    public boolean tryLock() {
        boolean result;
        // 加入自旋
        while (!(result = atomicInteger.compareAndSet(0, 1))) {
            System.out.println(Thread.currentThread() + ",自旋中.....");
        }
        lockCurrentThread = Thread.currentThread();
        System.out.println(lockCurrentThread + ",获取锁成功");
        return result;
    }

    //释放锁
    public boolean unLock() {
        // 只有获取到锁的线程才能释放锁
        if (lockCurrentThread != null && lockCurrentThread != Thread.currentThread()) {
            return false;
        }
        return atomicInteger.compareAndSet(1, 0);
    }

    public static void main(String[] args) {
        AtomicTryLock atomicTryLock = new AtomicTryLock();
        IntStream.range(1, 10).forEach((i) -> new Thread(() -> {
            // 不管发生什么，线程结束都需要释放锁
            try {
                atomicTryLock.tryLock();
            } catch (Exception e) {
                e.printStackTrace();
                atomicTryLock.unLock();
            } finally {
                atomicTryLock.unLock();
            }
        }).start());
    }


}